package com.example.controller.pc;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.annotation.Log;
import com.example.common.result.Result;
import com.example.entity.dto.pc.GetProductLineMachineHzViewDto;
import com.example.entity.dto.pc.GetResourcePlusByResourceParentIdDto;
import com.example.entity.dto.pc.GetSpecificResourceListDto;
import com.example.entity.dto.pc.ResourceGroupListDto;
import com.example.entity.hz.MOCTA;
import com.example.entity.mysql.*;
import com.example.entity.vo.pc.MoctyPlus;
import com.example.entity.vo.pc.ResourceGroupVo;
import com.example.entity.vo.pc.ResourcePlus;
import com.example.entity.yifei.Mocty;
import com.example.enums.MOCStatusEnum;
import com.example.enums.MachineStatusEnum;
import com.example.mapper.MoctaMapper;
import com.example.mapper.MoctyMapper;
import com.example.mapper.SFCTEMapper;
import com.example.mapper.pc.ProductprocessresourceMapper;
import com.example.mapper.pc.ResourceMapper;
import com.example.mapper.pc.ResourcesubMapper;
import com.example.service.pc.ProductprocessresourceService;
import com.example.service.pc.ResourceService;
import com.example.service.pc.ResourcegroupService;
import com.example.service.pc.WorkresourceService;
import com.example.untils.BeanUtils;
import com.example.untils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiangPandeng
 * @since 2024-05-19
 */
@RestController
@Api(tags = "资源组")
@RequestMapping("/api/resourcegroup")
public class ResourcegroupController {

    @Autowired
    private ProductprocessresourceService productprocessresourceService;
    @Autowired
    private ProductprocessresourceMapper productprocessresourceMapper;
    @Autowired
    private ResourcegroupService resourceGroupService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private SFCTEMapper sfcteMapper;
    @Autowired
    private MoctyMapper moctyMapper;
    @Autowired
    private MoctaMapper moctaMapper;
    @Autowired
    private WorkresourceService workresourceService;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private ResourcesubMapper resourcesubMapper;

    @Log("添加资源组")
    @ApiOperation("添加资源组")
    @PostMapping("addResourceGroup")
    @DSTransactional
    public Result addResourceGroup(@RequestBody Resourcegroup resourcegroup) {
        if(StringUtils.isEmpty(resourcegroup.getResourceGroupNO())
                || StringUtils.isEmpty(resourcegroup.getResourceGroupName())
                )  {
            return Result.error("资源组名或资源组编号为空");
        }
        Resourcegroup fa = resourceGroupService.getById(resourcegroup.getResourceGroupParentId());
        if(resourcegroup.getResourceGroupParentId() != null) {
            if(fa == null) {
                return Result.error("父节点不存在");
            }
            if("F".equals(fa.getType())) {
                return Result.error("父节点为具体组资源，不能新增子节点");
            }
            if("C".equals(fa.getType()) && "F".equals(resourcegroup.getType()))  {
                return Result.error("父节点类型为分类，不能新增末级");
            }
        }
        int nums = resourceGroupService.count(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupNO, resourcegroup.getResourceGroupNO()));
        if(nums > 0) {
            return Result.error("资源组编号不能重复!");
        }
        resourcegroup.setResourceGroupId(null);
        resourceGroupService.save(resourcegroup);
        Integer originId = resourceGroupService.getOriginIdById(resourcegroup.getResourceGroupParentId());

        // 【设备 | 生产线】的同步添加操作
        if("F".equals(resourcegroup.getType()) && (originId.equals(1) || originId.equals(2) || originId.equals(3) || originId.equals(4)) ) {
            Resource resource = new Resource();
            resource.setResourceType(originId);
            resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
            resource.setResourceGroupId(resourcegroup.getResourceGroupParentId());
            resource.setDeviceid(resourcegroup.getResourceGroupNO());
            resource.setDevicename(resourcegroup.getResourceGroupName());
            resource.setStatus(MachineStatusEnum.XianZhi.getValue());
            resourceService.save(resource);
            if(originId.equals(2)) {  // 判断生产线统驭是不是需要新增
                if(resourceService.count(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, resourcegroup.getResourceGroupParentId())) == 0) {
                    Resource resource2 = new Resource();
                    resource2.setResourceType(2);
                    resource2.setResourceGroupIdIsF(fa.getResourceGroupId());
                    resource2.setResourceGroupId(resourceGroupService.getById(fa.getResourceGroupParentId()).getResourceGroupId());
                    resource2.setDeviceid(fa.getResourceGroupNO());
                    resource2.setDevicename(fa.getResourceGroupName());
                    resourceService.save(resource2);
                }
            }
        }
        return Result.success("资源组添加成功");
    }

    @Log("修改资源组")
    @ApiOperation("修改资源组")
    @PostMapping("editResourceGroup")
    @DSTransactional
    public Result editResourceGroup(@RequestBody Resourcegroup resourcegroup) {
        if(StringUtils.isEmpty(resourcegroup.getResourceGroupNO())
                || StringUtils.isEmpty(resourcegroup.getResourceGroupName())
                || resourcegroup.getResourceGroupId() == null || StringUtils.isEmpty(resourcegroup.getType()))
        {
            return Result.error("资源组名或资源组编号或ID为空或类型为空");
        }
        if("F".equals(resourcegroup.getType())) {
            int count = resourceGroupService.count(new LambdaQueryWrapper<Resourcegroup>()
                    .eq(Resourcegroup::getResourceGroupParentId, resourcegroup.getResourceGroupId()));
            if(count > 0) {
                return Result.error("节点类型为具体组资源，不能有子节点");
            }
        }
        Resourcegroup xxx = resourceGroupService.getOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupNO, resourcegroup.getResourceGroupNO()));
        if(xxx != null && !xxx.getResourceGroupId().equals(resourcegroup.getResourceGroupId())) {
            return Result.error("资源组编号不能重复!");
        }
        // 特判，M-》F 且上级为C的情况 (因为工装现在不受管理)
        if("F".equals(resourcegroup.getType())) {
            Resourcegroup zhi = resourceGroupService.getById(resourcegroup.getResourceGroupParentId());
            if("C".equals(zhi.getType())) {
                return Result.error("[目录]类型下不能有[末级]类型!");
            }
        }
        Resourcegroup originData = resourceGroupService.getById(resourcegroup.getResourceGroupId());
        Integer originId = resourceGroupService.getOriginIdById(resourcegroup.getResourceGroupParentId());
        if("F".equals(resourcegroup.getType()) && (originId.equals(1) || originId.equals(2) || originId.equals(3) || originId.equals(4))) {
            Resourcegroup zhi = resourceGroupService.getById(resourcegroup.getResourceGroupParentId());
            if("C".equals(zhi.getType())) {
                return Result.error("[目录]类型下不能有[末级]类型!");
            }
            Resource resource = new Resource();
            resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
            resource.setResourceGroupId(resourcegroup.getResourceGroupParentId());
            resource.setDeviceid(resourcegroup.getResourceGroupNO());
            resource.setDevicename(resourcegroup.getResourceGroupName());
            if("M".equals(originData.getType())) {   // 从统驭到末级(M -> F)。resource表相当于新增。   从统驭到末级首先要把里面的都删除完。所以不会存在统驭的M在resource中
                Integer originIdById = resourceGroupService.getOriginIdById(resourcegroup.getResourceGroupId());
                resource.setResourceType(originIdById);
                resourceService.save(resource);
                //  生产线特有的操作： 判断上级的情况。如果上级不在resource中且上级不是C（目录）则需要新增一个到resource中
                if(originId.equals(2) && resourceService.count(new LambdaQueryWrapper<Resource>()
                        .eq(Resource::getResourceGroupIdIsF, resourcegroup.getResourceGroupParentId())) == 0) // 如果resource中没有
                {
                    // 把需要修改的上级，添加到里面
                    Resource t = new Resource();
                    t.setResourceGroupIdIsF(zhi.getResourceGroupId());
                    t.setResourceGroupId(zhi.getResourceGroupParentId());
                    t.setDeviceid(zhi.getResourceGroupNO());
                    t.setDevicename(zhi.getResourceGroupName());
                    t.setResourceType(2);
                    resourceService.save(t);
                }
            }else{   // F到F
                // 拿到原来的Resource值
                Resource one = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, originData.getResourceGroupId()));
                resource.setResourceid(one.getResourceid());
                resourceService.updateById(resource);
            }
        }
        resourceGroupService.updateById(resourcegroup);
        if("M".equals(resourcegroup.getType()) && "F".equals(originData.getType()) && (originId.equals(1) || originId.equals(2) || originId.equals(3) || originId.equals(4))) {  //  从F到M  是统驭的话。直接把值给删掉。
            resourceService.remove(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, originData.getResourceGroupId()));
            if(originId.equals(2)) {  // 如果是生产线的话，需要判断上级的F是否被用完了。
                int f = resourceGroupService.count(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getType, "F")
                        .eq(Resourcegroup::getResourceGroupParentId, resourcegroup.getResourceGroupParentId()));
                if(f == 0) {  // 用完了就把resource中的统驭给删除
                    resourceService.remove(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, resourcegroup.getResourceGroupParentId()));
                    // 删除资源子表的值
                    resourcesubMapper.delete(new LambdaQueryWrapper<Resourcesub>().eq(Resourcesub::getResourceGroupId, resourcegroup.getResourceGroupParentId()));
                }
            }
        }
        if("M".equals(resourcegroup.getType()) && "M".equals(originData.getType()) && (originId.equals(2))) {   // M到M  && 生产线统驭同步更新
            Resource resource = new Resource();
            resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
            resource.setResourceGroupId(resourcegroup.getResourceGroupParentId());
            resource.setDeviceid(resourcegroup.getResourceGroupNO());
            resource.setDevicename(resourcegroup.getResourceGroupName());
            resourceService.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, resourcegroup.getResourceGroupId()));
        }
        return Result.success("资源组修改成功");
    }

    @Log("删除资源组")
    @ApiOperation("删除资源组")
    @PostMapping("delResourceGroup")
    @DSTransactional
    public Result delResourceGroup(@RequestBody Integer id) {
        if(id == null) {
            return Result.error("id不能为空");
        }
        // 如果是删除资源组，判断资源组不能被使用过。（品号工序资源管理， 生产排产）
        int count = productprocessresourceService.count(new LambdaQueryWrapper<Productprocessresource>()
                .eq(Productprocessresource::getResourceGroupId, id));
        if(count > 0) {
            return Result.error("品号工序资源管理中，数据已被使用。");
        }
        count = workresourceService.count(new LambdaQueryWrapper<Workresource>().eq(Workresource::getResourceGroupId, id));
        if(count > 0) {
            return Result.error("[排产]--[生产线/设备]管理中，数据已被使用。");
        }
        count = resourcesubMapper.selectCount(new LambdaQueryWrapper<Resourcesub>().eq(Resourcesub::getDeviceResourceGroupId, id));
        if(count > 0) {
            return Result.error("[生产线管理]-[生产线/设备]中，数据已被使用。");
        }
        count = resourceGroupService.count(new LambdaQueryWrapper<Resourcegroup>()
                .eq(Resourcegroup::getResourceGroupParentId, id));
        if(count > 0) {
            return Result.error("请先删除下面的数据");
        }
        Integer originId = resourceGroupService.getOriginIdById(id);
        Resourcegroup needDel = resourceGroupService.getById(id);
        boolean b = resourceGroupService.removeById(id);
        if("F".equals(needDel.getType()) && (originId.equals(1) || originId.equals(2) || originId.equals(3) || originId.equals(4))) {   // 如果资源属于【机器 | 生产线】，则删除机器管理中的一一对应的资源
            resourceService.remove(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, id));
            if(originId.equals(2)) {  // 生产线末级删除的时候，需要判断上级的F有多少个，一个都没有了就直接删除
                int f = resourceGroupService.count(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupParentId, needDel.getResourceGroupParentId())
                        .eq(Resourcegroup::getType, "F"));
                if(f == 0) {
                    resourceService.remove(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, needDel.getResourceGroupParentId()));
                    // 删除资源子表的值
                    resourcesubMapper.delete(new LambdaQueryWrapper<Resourcesub>().eq(Resourcesub::getResourceGroupId, needDel.getResourceGroupParentId()));
                }
            }
        }
        if(b) return Result.success("删除成功");
        return Result.error("删除失败");
    }

    @ApiOperation("资源组列表(树形展示)")
    @PostMapping("resourcegroupList")
    public Result<ResourceGroupVo> resourcegroupList(@RequestBody ResourceGroupListDto dto) {
//        LambdaQueryWrapper<Resourcegroup> wrapper = new LambdaQueryWrapper<>();
//        if(StringUtils.isNotEmpty(dto.getResourceGroupName())) {
//            wrapper.eq(Resourcegroup::getResourceGroupName, dto.get)
//        }
        List<Resourcegroup> list = resourceGroupService.list();
//        return Result.success(ReportHelper.buildTree(list));

        Map<Integer, List<Resourcegroup>> map = new HashMap<>();  // 通过groupId,找下级的儿子
        Map<Integer, Resourcegroup> posMap = new HashMap<>();    // id 找对应的实体类
        for(Resourcegroup group : list) {
            posMap.put(group.getResourceGroupId(), group);
            List<Resourcegroup> resourcegroupList =
                    map.get(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId());
            if(resourcegroupList == null) {
                resourcegroupList = new ArrayList<>();
            }
            resourcegroupList.add(group);
            map.put(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId(), resourcegroupList);
        }
//        ResourceGroupVo res = new ResourceGroupVo();
        ResourceGroupVo res = getRes(map, posMap, dto.getResourceTypeId() == null ? 0 : dto.getResourceTypeId());
        return Result.success(res);
    }

    /**
     * 查询某个id节点下面的，所有树数据
     * @param map
     * @param posMap
     * @param id
     * @return
     */
    public ResourceGroupVo getRes(Map<Integer, List<Resourcegroup>> map, Map<Integer, Resourcegroup> posMap,
                                  Integer id) {
        ResourceGroupVo res = new ResourceGroupVo();
        if(id > 0) {
            Resourcegroup resourcegroup = posMap.get(id);
            if(resourcegroup != null) BeanUtils.copyPropertiesIgnoreCase(resourcegroup, res);
        }
        List<Resourcegroup> list = map.get(id);
        if(list == null) return res;
//        List<ResourceGroupVo> sonGroup = res.getSonGroup();
//        if(sonGroup == null) sonGroup = new ArrayList<>();
        List<ResourceGroupVo> sonGroup = new ArrayList<>();
        int nums = 0;
        for(Resourcegroup resourcegroup : list) {
            if("F".equals(resourcegroup.getType())) nums++;
            ResourceGroupVo vo = getRes(map, posMap, resourcegroup.getResourceGroupId());
//            sonGroup.add(getRes(map, posMap, resourcegroup.getResourceGroupId()));
            sonGroup.add(vo);
        }
        res.setFNums(nums);
        res.setSonGroup(sonGroup);
        return res;
    }

    @ApiOperation("资源组四大类")
    @PostMapping("topResourceGroup")
    public Result<List<Resourcegroup>> topResourceGroup() {
        List<Resourcegroup> list = resourceGroupService.list(new LambdaQueryWrapper<Resourcegroup>()
                .isNull(Resourcegroup::getResourceGroupParentId));
        return Result.success(list);
    }

    @ApiOperation("查询id下面资源组为统驭的  设备维护传1  生产线维护传2  模具3  工装4")
    @PostMapping("resourceGroupIsM")
    public Result<List<Resourcegroup>> resourceGroupIsM(@RequestBody(required = false) Integer id) {
        if(id == null) {
            return Result.success(resourceGroupService.list(new LambdaQueryWrapper<Resourcegroup>()
                    .eq(Resourcegroup::getType, "M")));
        }
        List<Resourcegroup> list = resourceGroupService.list(new LambdaQueryWrapper<Resourcegroup>()
                .and(i -> i.eq(Resourcegroup::getType, "M").or().eq(Resourcegroup::getType, "C")));   // 拿到数据库所有数据
        Map<Integer, List<Resourcegroup>> map = new HashMap<>();  // 用key 找 所有他的统驭儿子
        Map<Integer, Resourcegroup> posMap = new HashMap<>();   // key 找 自己的实体类
        for(Resourcegroup group : list) {
            posMap.put(group.getResourceGroupId(), group);
            List<Resourcegroup> resourcegroupList =
                    map.get(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId());
            if(resourcegroupList == null) {
                resourcegroupList = new ArrayList<>();
            }
            resourcegroupList.add(group);
            map.put(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId(), resourcegroupList);
        }
        List<Resourcegroup> res = getM(map, posMap, id);
        return Result.success(res);
    }

    /**
     * 有预设值的，查出预设值中的末级资源
     * 没有的，查出全部。（生产线/机器需要分工作中心）
     * @param dto
     * @return
     */
    @ApiOperation("查看所有的末级资源")
    @PostMapping("getSpecificResourceList")
    public Result<List<ResourcePlus>> getSpecificResourceList(@RequestBody GetSpecificResourceListDto dto) {
        if(dto.getResourceType() == null) {
            return Result.error("设备类型不能为空");
        }
        if(StringUtils.isEmpty(dto.getWorkCenter())) {
            return Result.error("工作中心不能为空");
        }
        List<ResourcePlus> list = null;
        List<Productprocessresource> productprocessresourceList = null;
        // 先查看有没有预设值。
        if(dto.getResourceType().equals(1) || dto.getResourceType().equals(2)) {
            // 生产线/设备需要查询工作中心
            productprocessresourceList = productprocessresourceMapper.selPPRListHzVersion(
                    new GetProductLineMachineHzViewDto(dto.getProductId(), dto.getProcessNo(), dto.getProcessId(), dto.getInvrtName(),
                            dto.getProcessRoute(), dto.getWorkCenter(), dto.getInvNo(), dto.getResourceType(), null));
        }else if(!"ST4".equals(dto.getWorkCenter().trim()) && !"ST6".equals(dto.getWorkCenter().trim())){  // 装配相关的，直接查全部。所以直接跳过这里
            productprocessresourceList = productprocessresourceMapper.selPPRListHzVersion(
                    new GetProductLineMachineHzViewDto(dto.getProductId(), dto.getProcessNo(), dto.getProcessId(), dto.getInvrtName(),
                            dto.getProcessRoute(), null, dto.getInvNo(), dto.getResourceType(), null));
        }
        // 有的话，只能用这里面的
        if(productprocessresourceList != null && productprocessresourceList.size() > 0) {  // 如果之前有预设值
            GetResourcePlusByResourceParentIdDto dto1 = new GetResourcePlusByResourceParentIdDto();
            dto1.setVal(dto.getVal());
            if(dto.getResourceType().equals(1) || dto.getResourceType().equals(2)) {    //  1和2的话，需要查询工作中心
                dto1.setWorkCenter(dto.getWorkCenter());
            }
            List<Integer> resourceParentIdList = new ArrayList<>();
            for(Productprocessresource t : productprocessresourceList) {
                if(t.getResourceGroupId() != null && !t.getResourceGroupId().equals(0)) resourceParentIdList.add(t.getResourceGroupId());
            }
            dto1.setResourceParentIdList(resourceParentIdList);
            List<ResourcePlus> resourcePlusList = resourceMapper.getResourcePlusByResourceParentId(dto1);
            if(resourcePlusList.size() == 0 && (dto.getResourceType().equals(1) || dto.getResourceType().equals(2))) {  // 如果预设值里面没有匹配到任意一个的话
                dto1.setWorkCenter(null);
                resourcePlusList = resourceMapper.getResourcePlusByResourceParentId(dto1);
                String deviceId = "";
                if(resourcePlusList.size() > 0) {
                    deviceId = resourcePlusList.get(0).getResourceGroupName().trim();
                    resourcePlusList = resourceMapper.getResourcePlusByWorkCenterAndDeviceId(deviceId, dto.getWorkCenter(), dto.getVal());
                }
            }
            if(dto.getResourceType().equals(1)) {  // 如果是机器的话
                for(ResourcePlus item : resourcePlusList) {
                    if(StringUtils.isNotEmpty(item.getMoctyudf05())) {
                        // 查看目前已报工数量
//                        BigDecimal bgNums = sfcteMapper.getAlreadyBGmocty(item.getMoctyudf05());
//                        item.setBgNums(bgNums);
                        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, item.getMoctyudf05()));
                        if(mocty != null) {
                            MOCTA mocta = moctaMapper.selectOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, mocty.getTy001())
                                    .eq(MOCTA::getTA002, mocty.getTy002()));
                            item.setMoctyNums(new BigDecimal(mocty.getTy004()));
                            item.setMacOnTime(mocty.getUdf07());
                            item.setProductionNums(mocta.getTA017());
                            item.setTy001(mocty.getTy001());
                            item.setTy002(mocty.getTy002());
                            List<Workresource> workresourceList = workresourceService.list(new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, item.getMoctyudf05())
                                    .eq(Workresource::getResourceId, item.getResourceGroupId()));
                            item.setBeat(workresourceList.get(0).getBeat().toString());
//                            Resource resource = resourceService.getOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMachineNo()));
                        }
                    }
                    List<String> statusList = new ArrayList<>();
                    statusList.add(MOCStatusEnum.DaiShouJian.getValue());  statusList.add(MOCStatusEnum.ShouJianZhong.getValue());
                    statusList.add(MOCStatusEnum.DaiJinZhan.getValue());  statusList.add(MOCStatusEnum.ShengChanZhong.getValue());
                    statusList.add(MOCStatusEnum.DaiKaiJi.getValue()); statusList.add(MOCStatusEnum.ZanTing.getValue());
                    statusList.add(MOCStatusEnum.DaiShangLiaoQueRen.getValue()); statusList.add(MOCStatusEnum.DaiMuJuQueRen.getValue());

                    List<MoctyPlus> moctyList = moctyMapper.moctyListByResourceId(null, item.getResourceGroupId().toString(), statusList);
                    for(MoctyPlus t : moctyList) {
                        t.setMacOnTime(t.getUdf07());
                        List<Workresource> wrl = workresourceService.list(new LambdaQueryWrapper<Workresource>()
                                .eq(Workresource::getProductLineId, t.getUdf05())
                                .eq(Workresource::getResourceId, item.getResourceGroupId()));
                        if(wrl != null && wrl.size() > 0) t.setBeat(wrl.get(0).getBeat().toString());
                    }
                    item.setMoctyPluslist(moctyList);
                }
            }
            return Result.success(resourcePlusList);
        }

        // 没有预设值的话
        if(dto.getResourceType().equals(1)) {
            list = resourceMapper.getResourcePlus(dto);
            for(ResourcePlus item : list) {
                if(StringUtils.isNotEmpty(item.getMoctyudf05())) {
                    // 查看目前已报工数量
//                    BigDecimal bgNums = sfcteMapper.getAlreadyBGmocty(item.getMoctyudf05());
//                    item.setBgNums(bgNums);
                    Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, item.getMoctyudf05()));
                    if(mocty != null) {
                        item.setMoctyNums(new BigDecimal(mocty.getTy004()));
                        MOCTA mocta = moctaMapper.selectOne(new LambdaQueryWrapper<MOCTA>().eq(MOCTA::getTA001, mocty.getTy001())
                                .eq(MOCTA::getTA002, mocty.getTy002()));
                        item.setProductionNums(mocta.getTA017());
                    }
                }
            }
        }else if(dto.getResourceType().equals(2)){
            list = resourceMapper.getResourcePlus(dto);
        }else if(dto.getResourceType().equals(3)) {  // 模具和工装不区分工作中心
            dto.setWorkCenter(null);
            list = resourceMapper.getResourcePlusMould(dto);
        }else if(dto.getResourceType().equals(4)) {
            dto.setWorkCenter(null);
            list = resourceMapper.getResourcePlus(dto);
        }
        for(ResourcePlus t : list) {
            if(StringUtils.isNotEmpty(t.getMoctyudf05())) {
                Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, t.getMoctyudf05()));
                if(mocty != null) {
                    t.setMacOnTime(mocty.getUdf07());
                    t.setTy001(mocty.getTy001());
                    t.setTy002(mocty.getTy002());
                    List<Workresource> workresourceList = workresourceService.list(new LambdaQueryWrapper<Workresource>()
                            .eq(Workresource::getProductLineId, t.getMoctyudf05())
                            .eq(Workresource::getResourceId, t.getResourceGroupId()));
                    if(workresourceList != null && workresourceList.size() > 0) t.setBeat(workresourceList.get(0).getBeat().toString());
                }
            }
            List<String> statusList = new ArrayList<>();
            statusList.add(MOCStatusEnum.DaiShouJian.getValue());  statusList.add(MOCStatusEnum.ShouJianZhong.getValue());
            statusList.add(MOCStatusEnum.DaiJinZhan.getValue());  statusList.add(MOCStatusEnum.ShengChanZhong.getValue());
            List<MoctyPlus> moctyList = moctyMapper.moctyListByResourceId(null, t.getResourceGroupId().toString(), statusList);
            for(MoctyPlus x : moctyList) {
                x.setMacOnTime(x.getUdf07());
                List<Workresource> wrl = workresourceService.list(new LambdaQueryWrapper<Workresource>()
                        .eq(Workresource::getProductLineId, x.getUdf05())
                        .eq(Workresource::getResourceId, t.getResourceGroupId()));
                if(wrl != null && wrl.size() > 0) x.setBeat(wrl.get(0).getBeat().toString());
            }
            t.setMoctyPluslist(moctyList);
        }
        return Result.success(list);
    }

    @ApiOperation("查询id下面资源组为末级的  设备维护传1  生产线维护传2  模具3  工装4")
    @PostMapping("resourceGroupIsF/{id}")
    public Result<List<Resourcegroup>> resourceGroupIsF(@PathVariable Integer id) {
        if(id == null) {
            return Result.success(resourceGroupService.list(new LambdaQueryWrapper<Resourcegroup>()
                    .eq(Resourcegroup::getType, "F")));
        }
        List<Resourcegroup> list = resourceGroupService.list(null);   // 拿到数据库所有数据
        Map<Integer, List<Resourcegroup>> map = new HashMap<>();  // 用key 找 所有他的统驭儿子
        Map<Integer, Resourcegroup> posMap = new HashMap<>();   // key 找 自己的实体类
        for(Resourcegroup group : list) {
            posMap.put(group.getResourceGroupId(), group);
            List<Resourcegroup> resourcegroupList =
                    map.get(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId());
            if(resourcegroupList == null) {
                resourcegroupList = new ArrayList<>();
            }
            resourcegroupList.add(group);
            map.put(group.getResourceGroupParentId() == null ? 0 : group.getResourceGroupParentId(), resourcegroupList);
        }
        List<Resourcegroup> res = getF(map, posMap, id);
        return Result.success(res);
    }

    /**
     * 查询某个点下面，为末级的资源组
     * @param map
     * @param posMap
     * @param id
     * @return
     */
    private List<Resourcegroup> getF(Map<Integer, List<Resourcegroup>> map, Map<Integer, Resourcegroup> posMap,
                                     Integer id) {
        List<Resourcegroup> res = new ArrayList<>();
        Resourcegroup resourcegroup = posMap.get(id);
        if(resourcegroup != null && "F".equals(resourcegroup.getType())) {
            res.add(resourcegroup);
        }
        List<Resourcegroup> list = map.get(id);
        if(list != null && list.size() > 0) {
            for(Resourcegroup t : list) {
                List<Resourcegroup> f = getF(map, posMap, t.getResourceGroupId());
                if(f != null && f.size() > 0) {
                    for(Resourcegroup fson : f) {
                        res.add(fson);
                    }
                }
            }
        }
        return res;
    }

    /**
     * 查询某个点下面，为统驭的资源组
     * @param map
     * @param posMap
     * @param id
     * @return
     */
    private List<Resourcegroup> getM(Map<Integer, List<Resourcegroup>> map, Map<Integer, Resourcegroup> posMap,
                                     Integer id) {
        List<Resourcegroup> res = new ArrayList<>();
        Resourcegroup resourcegroup = posMap.get(id);
        if(resourcegroup != null && "M".equals(resourcegroup.getType())) res.add(resourcegroup);
        List<Resourcegroup> list = map.get(id);
        if(list != null && list.size() > 0) {
            for(Resourcegroup t : list) {
                List<Resourcegroup> f = getM(map, posMap, t.getResourceGroupId());
                if(f != null && f.size() > 0) {
                    for(Resourcegroup fson : f) {
                        res.add(fson);
                    }
                }
            }
        }
        return res;
    }

    @ApiOperation("查询id的末级儿子")
    @PostMapping("fSonList/{id}")
    public Result<List<Resourcegroup>> fSonList(@PathVariable Integer id) {
        return Result.success(resourceGroupService.list(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupParentId, id).eq(Resourcegroup::getType, "F")));
    }

}
